<template>
  <el-dialog title="抽检详情" :visible.sync="detail.show" width="1200px" append-to-body>
    <div class="course-project">
      <div class="detail-item"><span>所属部门：</span><span>{{ courseRow.showDeptName }}</span></div>
      <div class="detail-item"><span>项目：</span><span>{{ courseRow.projectName }}</span></div>
      <div class="detail-item"><span>施工单位：</span><span>{{ courseRow.constructionName }}</span></div>
      <div class="detail-item" v-if="courseRow.constructionUser"><span>施工单位负责人：</span><span>{{ courseRow.constructionUser }}</span></div>
      <div class="detail-item" v-if="!isConstruction"><span>标段：</span><span>{{ courseRow.section }}</span></div>
      <div class="detail-item"><span>检查人员：</span><span>{{ courseRow.principalUserName || '/' }}</span></div>
      <div class="detail-item"><span>检查时间：</span><span>{{ courseRow.checkDate }}</span></div>
      <div class="detail-item" v-if="isConstruction"><span>检查类型：</span><span>{{ courseRow.progressChkType | dictFilter(dict.type.cq_progress_chk_type) }}</span></div>
    </div>
    <div class="score-list">
      <div class="item" v-for="item in scoreTypeList" :key="item.chkitemId">
        <div class="label" style="font-weight: bold">
          <span>{{ item.chkitemName }} </span>
          <!-- <div v-if="!item.children" /> -->
          <span class="score" :class="item.scoreResult">
            <span>{{ item.scoreLevel }}</span>
            <span v-if="item.scoreInput">({{ item.scoreInput }})</span>
          </span>
        </div>
        <div class="children" v-if="item.children">
          <div class="item item2" v-for="sub in item.children" :key="sub.chkitemId">
            <div class="label">
              <span>{{ sub.chkitemName }} </span>
              <div v-if="!sub.haveProductType" />
              <span class="score" :class="sub.scoreResult">{{ sub.scoreInput }}</span>
            </div>
            <div class="children" v-if="sub.children">
              <div class="item item3" v-for="(productType, pindex) in sub.children" :key="'productType' + pindex">
                <div>{{ productType.chkitemName }}</div>
                <span class="score" :class="productType.scoreResult">{{ productType.scoreInput }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-tabs v-model="activeName" @tab-click="tabClick" :class="{ disabled: detail.loading }">
      <template v-for="item in scoreTypeList">
        <template v-if="item.children && item.children.length > 0">
          <el-tab-pane :label="sub.chkitemName" :name="sub.chkitemCode" v-for="sub in item.children" :key="sub.chkitemCode" />
        </template>
        <el-tab-pane v-else :label="item.chkitemName" :name="item.chkitemCode" :key="item.chkitemCode" />
      </template>
    </el-tabs>
    <el-tabs v-model="currProductType" @tab-click="tabClickProductType" type="card" class="product-type-tab" :class="{ disabled: detail.loading }" v-if="showProductTypeTab">
      <el-tab-pane :label="dict.label" :name="dict.value" v-for="dict in dict.type.cq_product_type" :key="dict.value" />
    </el-tabs>
    <el-checkbox
      v-if="isConstruction && activeName === SCORE_TYPE.FSL"
      v-model="courseRow.fslIsDlsyUnsuit"
      :true-label="1"
      :false-label="0"
      text-color="#FF3E4C"
      disabled
      class="detail-dlsy-unsuit"
    >独立商业检查为C级</el-checkbox>
    <el-table
      ref="tableRef"
      v-loading="detail.loading"
      :data="detail.list"
      height="50vh"
      :show-summary="activeName == 'zl-scsl'"
      style="width: 100%;"
      @expand-change="tableExpandChange"
      @row-click="tableRowClick"
    >
      <el-table-column type="expand">
        <template slot-scope="props" v-if="props.row.result != -1">
          <process-detail v-loading="props.row.itemLoading" :row-data="props.row" />
        </template>
      </el-table-column>
      <el-table-column
        prop="mrqName"
        label="实测实量"
        min-width="90"
        align="center"
        key="column1"
        v-if="activeName == 'zl-scsl'"
      />
      <el-table-column
        prop="checkTotal"
        label="抽检数量"
        min-width="60"
        align="center"
        key="column2"
        v-if="activeName == 'zl-scsl'"
      />
      <el-table-column
        prop="goodTotal"
        label="合格数量"
        min-width="60"
        align="center"
        key="column3"
        v-if="activeName == 'zl-scsl'"
      >
        <template slot-scope="scope">
          <span :class="{red: parseInt(scope.row.goodTotal) < parseInt(scope.row.checkTotal)}">{{ scope.row.goodTotal }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="activeName == 'zl-atsg' || activeName == 'zl-clgl' ? '所属分类' : '所属工序'"
        min-width="120"
        key="column4"
      >
        <template slot-scope="scope">{{ scope.row.allTableName }}</template>
      </el-table-column>
      <el-table-column
        label="工序标准"
        min-width="400"
        key="column5"
      >
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            width="600"
            trigger="hover"
            :content="scope.row.standardContent"
          >
            <div class="process-standard" :class="{'red': scope.row.itemLevel == '2' || scope.row.itemLevel == '3'}" slot="reference">
              <span v-if="scope.row.itemLevel==3">*</span>
              {{ scope.row.standardContent }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        label="抽检状态"
        min-width="80"
        align="center"
        key="column6"
        v-if="activeName != 'zl-scsl'"
      >
        <template slot-scope="scope" v-if="activeName != 'zl-scsl'">
          <el-tag size="small" :type="scope.row.type | statusType('style')">{{ scope.row.type | statusType('desc') }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script>
import { inspectTypeListWithKey, cqProductType } from '@/utils/baseData'
import { selectItemAreaInfo, getScoreItemDetail } from '@/api/projectInspection/courseCheck'
import { selectItemDetail } from '@/api/checkScore/courseCheck.js'
import processDetail from './processDetail'
import { getFileURL } from '@/api/common'
import { RULE_TYPE, SCORE_TYPE } from '@/utils/baseData'

const productType2key = cqProductType.reduce((o, i) => !void (o[i.value] = i.key) && o, {})

// 移除 '管理动作'; '空鼓开裂'字段有差异，改为 zlKg
const inspectTypeList = JSON.parse(JSON.stringify(inspectTypeListWithKey))
inspectTypeList.map(item =>
  item.scoreTypeList.map((i, index) => {
    if (i.key === 'gldz') item.scoreTypeList.splice(index, 1)
    if (i.children) i.children.map(j => j.key === 'zlKgkl' && (j.key = 'zlKg'))
  })
)

export default {
  name: 'ConstructionDetail',
  dicts: ['cq_product_type', 'cq_progress_chk_type', 'cq_rectify_operate'],
  components: {processDetail},
  filters: {
    scoreClass(val, scoreType) {
      if (!val) return ''
      if (scoreType === 'fsl') {
        if (val === 'A') return 'blue'
        if (val === 'B' || val === 'C') return 'red'
        return ''
      }
      if (val === 'A' || val >= 90) return 'green'
      if (val === 'B' || (val < 90 && val >= 80)) return 'blue'
      if (val === 'C' || val < 80) return 'red'
      return ''
    },
    scoreName(item = {}, key, isLevel1) {
      // 一级大类才显示等级
      const level = isLevel1 ? item[`${key}Level`] || '' : ''
      const score = item[`${key}Score`] || ''
      const val = level ? `${level}${score ? `(${score})` : ''}` : score
      return val || '/'
    },
    statusType(val, type) {
      let str = ''
      let style = ''
      if (val === 'unqualified') {
        str = '不合格'
        style = 'danger'
      } else if (val === 'cannotcheck' || val === 'notcheck') {
        str = '甩项'
        style = 'warning'
      } else if (val === 'qualified') {
        str = '合格'
        style = 'success'
      }
      if (type === 'desc') {
        return str
      } else {
        return style
      }
    }
  },
  props: {
    cfg: {type: Object, default: () => ({})}
  },
  data() {
    return {
      scoreTypeList: [],
      SCORE_TYPE: SCORE_TYPE,
      productType2key,
      processType: '',
      detail: {
        show: false,
        loading: false,
        list: []
      },
      activeName: '',
      currProductType: '',
      courseRow: {},
      treeProps: {
        children: 'childList',
        label: 'standardContent'
      },
      treeData: [],
      isConstruction: false, // 是否土建
      showProductTypeTab: false
    }
  },
  computed: {
    scoreTypeWithProduct() {
      // 有抽检业态的检查项
      const list = []
      this.scoreTypeList.map(i => i.children?.map(j => j.haveProductType && list.push(j.value)))
      return list
    }
  },
  created() { // 初始化
    const path = this.$route.path
    this.isConstruction = path.includes('ConstructionCourse')
  },
  methods: {
    /*
    *  初始化
    * */
    init(row) {
      this.detail.show = true
      this.processType = row.processType
      this.courseRow = row
      const list = row.scores
      this.scoreTypeList = list
      if (list[0].children && list[0].children.length > 0) {
        this.activeName = list[0].children[0].chkitemCode
      } else {
        this.activeName = list[0].chkitemCode
      }
      this.selectItemDetail()
    },
    tableRowClick (row) {
      this.$refs.tableRef.toggleRowExpansion(row)
    },
    tableExpandChange(row, expand) {
      if (row.loaded || row.result === -1) return
      row.loaded = true
      const params = {scoreItemId: row.scoreItemId}
      row.itemLoading = true
      this.getScoreItemDetailByScoreItem(row)
      selectItemAreaInfo(params).then(
        response => {
          if (response.code === 200) {
            const dataList = response.data
            if (dataList.length > 0) {
              dataList.map(area => {
                // checked 初始化
                area.checked = false
                area.url = getFileURL(area.fileId)
                // 注：rectifyId 现用于判断从历史添加，此处暂不需要
                delete area.rectifyId
              })
              row.areaList = dataList
            } else {
              row.areaList = []
            }
          }
        }
      ).finally(() => {
        row.itemLoading = false
      })
    },
    // 根据 标准计分 获取验收情况列表
    getScoreItemDetailByScoreItem(row) {
      const query = {
        scoreItemId: row.scoreItemId
      }
      getScoreItemDetail(query).then(res => {
        if (res.code === 200) {
          if (res.data) {
            row.rectifyRecords = []
            if (res.data.rectifyRecords) {
              res.data.rectifyRecords.forEach(item => {
                if (item.sysFiles) {
                  item.sysFiles.forEach(file => {
                    file.url = getFileURL(file.id)
                    file.isImage = true
                    file.type = 'png'
                  })
                } else {
                  item.sysFiles = []
                }
              })
              row.rectifyRecords = res.data.rectifyRecords.sort((obj1, obj2) => {
                return obj1.updateTime.localeCompare(obj2.updateTime)
              })
            }
          }
        } else {
          this.$message.error(res.msg)
        }
      }).catch((err) => { // 接口请求错误处理
        console.error(err)
      })
    },
    handleNodeClick(data) {
      console.log(data)
    },
    tabClick() {
      // 重置抽检业态 tab
      this.showProductTypeTab = false
      for (let i = 0; i < this.scoreTypeList.length; i++) {
        if (this.scoreTypeList[i].children && this.scoreTypeList[i].children.length) {
          const clist = this.scoreTypeList[i].children
          for (let j = 0; j < clist.length; j++) {
            if (clist[j].chkitemCode === this.activeName) {
              if (clist[j].children && clist[j].children.length > 0) {
                this.showProductTypeTab = true
              }
            }
          }
        } else {
          if (this.scoreTypeList[i].chkitemCode === this.activeName) {
            if (this.scoreTypeList[i].children && this.scoreTypeList[i].children.length > 0) {
              this.showProductTypeTab = true
            }
          }
        }
      }
      const productTypes = this.dict?.type.cq_product_type || []
      if (productTypes.length) this.currProductType = productTypes[0].value
      this.selectItemDetail()
    },
    tabClickProductType() {
      this.selectItemDetail()
    },
    // 获取抽检数据详情
    selectItemDetail() {
      this.detail.loading = true
      const params = {
        prjchkId: this.courseRow.prjchkId,
        checkitemCode: this.activeName,
        versionCode: this.courseRow.versionCode
      }
      if (this.showProductTypeTab) params.productType = this.currProductType

      selectItemDetail(params).then(
        response => {
          if (response.code === 200) {
            this.detail.loading = false
            const data = response.data
            const list = []
            if (data.unqualified) {
              for (let i = 0; i < data.unqualified.length; i++) {
                list.push({ ...data.unqualified[i], type: 'unqualified'})
              }
            }
            if (data.qualified) {
              for (let i = 0; i < data.qualified.length; i++) {
                list.push({ ...data.qualified[i], type: 'qualified'})
              }
            }
            if (data.cannotcheck) {
              for (let i = 0; i < data.cannotcheck.length; i++) {
                list.push({ ...data.cannotcheck[i], type: 'cannotcheck'})
              }
            }
            if (data.notcheck) {
              for (let i = 0; i < data.notcheck.length; i++) {
                list.push({ ...data.notcheck[i], type: 'notcheck'})
              }
            }
            list.sort((a, b) => {
              // if (a.type !== b.type) return (a.type || '').localeCompare(b.type || '')
              if (a.type !== b.type) return
              return (a.tableCode || '').localeCompare(b.tableCode || '')
            })
            list.forEach(item => {
              item.areaList = []
              item.loaded = false
              item.itemLoading = false
              item.deductArr = []
              // 观感 户内 公区展示
              const deductArr = []
              if (item.deductJson) {
                try {
                  item.deductJson = JSON.parse(item.deductJson)
                } catch (e) {
                  console.log(e)
                }
                for (const key in item.deductJson) {
                  let label = null
                  if (key.includes('room')) {
                    label = key.replace('room', '房')
                  }
                  if (key.includes('build')) {
                    label = key.replace('build', '楼')
                  }
                  const count = parseInt(label.substr(label.length - 1, 1)) + 1
                  label = label.substr(0, 1) + count
                  deductArr.push({
                    label: label,
                    key: key,
                    value: item.deductJson[key]
                  })
                }
                item.deductArr = deductArr
              }
              // 工序名称
              const tableNames = []
              if (item.parentTableName) {
                tableNames.push(item.parentTableName)
              }
              if (item.tableName) {
                tableNames.push(item.tableName)
              }
              item.allTableName = tableNames.join(' - ')
              // 条件条款
              if (item.ruleType === RULE_TYPE.TJTK) {
                let conditionOptions = []
                try {
                  conditionOptions = JSON.parse(item.ruleJson)
                } catch (e) {
                  console.log(e)
                }
                item.conditionOptions = conditionOptions
              }
            })
            this.detail.list = list

            // 重置表格高度和滚动
            this.$nextTick(() => {
              const ref = this.$refs.tableRef
              if (!ref) return
              ref.doLayout()
              ref.bodyWrapper.scrollTop = 0
            })
          }
        }
      )
    }
  }
}
</script>

<style scoped lang='scss'>
  .course-project {
    display: flex;
    flex-wrap: wrap;
    border-bottom: 1px solid #E4E7ED;
    padding-bottom: 10px;
    margin-bottom: 20px;
    margin-top: -20px;
    .detail-item {
      padding-bottom: 10px;
      margin:0 60px 0 0;
      span:nth-child(1) {
        display: inline-block;
        // width: 80px;
      }
      span:nth-child(2) {
        display: inline-block;
        min-width: 80px;
        font-weight: bold;
        background-color: #eff2f9;
        padding: 0 10px;
        height: 30px;
        line-height: 30px;
        border-radius: 4px;
        vertical-align: middle;
      }
    }
  }
.score-list {
  display: flex;
  flex-wrap: wrap;
  white-space: nowrap;
  text-align: center;
  margin-bottom: 10px;
  .children {
    display: flex;
  }
  .item {
    background-color: #f2f6fc;
    border-radius: 8px;
    padding: 10px;
    margin: 5px 5px 0;
    zoom: 0.96;
    // height: 100%;
    // display: flex;
    // justify-content: center;
    // flex-direction: column;
  }
  .item2 {
    background-color: #e1ecf4;
  }
  .item3 {
    background-color: #d2e4f0;
  }
  .score {
    font-weight: bold;
  }
}
.product-type-tab {
  zoom: 0.9;
  /deep/ .el-tabs__header {
    margin-bottom: 0;
  }
}
  .course-detail {
    display: flex;
    flex-wrap: wrap;
    .course-item {
      margin:0 40px 10px 0;
      span:nth-child(1) {
        display: inline-block;
        width: 80px;
      }
      span:nth-child(2) {
        display: inline-block;
        width: 110px;
        font-weight: bold;
        background-color: #eff2f9;
        padding: 0 10px;
        height: 30px;
        line-height: 30px;
        border-radius: 4px;
      }
    }
  }
  .process-standard {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .check-picture {
    font-size: 30px;
    cursor: pointer;
    color: #8ebae1;
  }
  $dlsyColor: #F56C6C;
  .detail-dlsy-unsuit {
    margin-bottom: 10px;
  }
  .detail-dlsy-unsuit/deep/.el-checkbox__input.is-checked + .el-checkbox__label {
    color: $dlsyColor;
  }
  .detail-dlsy-unsuit/deep/.el-checkbox__input.is-checked .el-checkbox__inner,
  .detail-dlsy-unsuit/deep/.el-checkbox__input.is-indeterminate .el-checkbox__inner {
    border-color: $dlsyColor !important;
    background-color: $dlsyColor !important;
  }
.EXCELLENT {
  color: #67c23a;
}
.VALID {
  color: #409eff;
}
.UNVALID {
  color: #f56c6c;
}
</style>
